package app.controller.wechat;

import java.awt.Image;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.scyf.bean.GlobalAccessToken;
import com.scyf.bean.ImageMessageBean;
import com.scyf.bean.TextMessageBean;
import com.scyf.bean.UploadTempMaterial;
import com.scyf.weixintool.WeiXinGlobalToken;
import com.scyf.weixintool.WeiXinMediaManage;
import com.scyf.weixintool.WeiXinMessageResolver;

import app.utils.FileDownloader;
import app.wechat.pojo.WeChat;

@Component("callbackwx")
public class SimpleAbsEventHandleImpl extends AbsEventHandle{
	@Autowired
	@Qualifier("wechat")
	private WeChat weChat;
	
	@Override
	public void IMAGEResolver(HttpServletResponse response, String xml) throws Exception {
		ImageMessageBean imageMessage = WeiXinMessageResolver.resolveImageMessage(xml);
		String picUrl = imageMessage.getPicUrl();
		URL url=new URL("https://www.3firelink.com/robot/Robot/v1");
		HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
		openConnection.setRequestMethod("POST");
		openConnection.setDoOutput(true);
		OutputStream outputStream = openConnection.getOutputStream();
		outputStream.write((picUrl+"?wx_fmt=png").getBytes());
		outputStream.flush();
		InputStream inputStream = openConnection.getInputStream();
		StringBuilder ans=new StringBuilder();
		String temp;
		BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
		while((temp=reader.readLine())!=null) {
			ans.append(temp);
		}
		if (!ans.toString().contains("http://")) {
			String responseXml = WeiXinMessageResolver.makeTextResponseXmlString(imageMessage.getFromUserName(),
					imageMessage.getToUserName(),
					ans.toString());
			response.setContentType("text/xml;charset=utf-8");
			PrintWriter writer =  new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"));
			writer.write(responseXml);
			writer.flush();
		}else {
			File file = new FileDownloader().file(ans.toString(), "/opt/filetemp");
			GlobalAccessToken accessToken = WeiXinGlobalToken.getGlobalAccessToken(weChat.getAppId(), weChat.getAppSecret());
			UploadTempMaterial uploadMedia = WeiXinMediaManage.uploadMedia(accessToken.getAccess_token(), file, "image");
			
			String media_id = uploadMedia.getMedia_id();
			
			String makeImageResponseXmlString = WeiXinMessageResolver.makeImageResponseXmlString(imageMessage.getFromUserName(),
					imageMessage.getToUserName(),
					media_id);
			response.setContentType("text/xml;charset=utf-8");
			PrintWriter writer =  new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"));
			writer.write(makeImageResponseXmlString);
			writer.flush();
			file.delete();
			return;
		}
	}
	
	@Override
	public void TEXTResolver(HttpServletResponse response, String xml) throws Exception {
		text(response, xml);
	}
	private void text(HttpServletResponse response, String xml) throws Exception{
		// TODO Auto-generated method stub
		String answer="您总要说点什么不是";
		TextMessageBean textMessage = WeiXinMessageResolver.resolveTextMessage(xml);
		if (textMessage.getContent().replace(" ", "").length()>0) {
			//连接机器人
			URL url=new URL("https://www.3firelink.com/robot/Robot/v1");
			HttpURLConnection openConnection = (HttpURLConnection) url.openConnection();
			openConnection.setRequestMethod("POST");
			openConnection.setDoOutput(true);
			OutputStream outputStream = openConnection.getOutputStream();
			outputStream.write(textMessage.getContent().getBytes());
			outputStream.flush();
			InputStream inputStream = openConnection.getInputStream();
			StringBuilder ans=new StringBuilder();
			String temp;
			BufferedReader reader=new BufferedReader(new InputStreamReader(inputStream));
			while((temp=reader.readLine())!=null) {
				ans.append(temp);
			}
			//
			answer=ans.toString();
		}
		//如果返回的是图片
		if (answer.contains("http://")&&(answer.contains(".png")||answer.contains(".jpg")||answer.contains(".gif"))) {
			//下载图片上传微信
			GlobalAccessToken accessToken = WeiXinGlobalToken.getGlobalAccessToken(weChat.getAppId(), weChat.getAppSecret());
			File file = new FileDownloader().file(answer, "/opt/filetemp");
			
			UploadTempMaterial uploadMedia = WeiXinMediaManage.uploadMedia(accessToken.getAccess_token(), file, "image");
			
			String media_id = uploadMedia.getMedia_id();
			
			String makeImageResponseXmlString = WeiXinMessageResolver.makeImageResponseXmlString(textMessage.getFromUserName(),
															 textMessage.getToUserName(),
															 media_id);
			response.setContentType("text/xml;charset=utf-8");
			PrintWriter writer =  new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"));
			writer.write(makeImageResponseXmlString);
			writer.flush();
			file.delete();
			return;
		}
		
		
		
		String responseXml = WeiXinMessageResolver.makeTextResponseXmlString(textMessage.getFromUserName(),
														textMessage.getToUserName(),
														answer);
		response.setContentType("text/xml;charset=utf-8");
		PrintWriter writer =  new PrintWriter(new OutputStreamWriter(response.getOutputStream(), "utf-8"));
		writer.write(responseXml);
		writer.flush();
	}
	
}
